<template>
	<div class="search-container">
		<form action="/" class="search-form">
			<van-search :clearable="false" @focus="isResultShow = false" v-model="searchText" background="#3296fa"
				show-action placeholder="请输入搜索关键词" @search="onSearch" @cancel="onCancel" />
		</form>

		<SearchResult v-if="isResultShow" :searchText="searchText"></SearchResult>
		<SearchSuggestion v-else-if="searchText" :searchText="searchText" @search="onSearch"></SearchSuggestion>
		<SearchHistory v-else @historySearch="historySearch" @clearHistory="clearHistory"
			:searchHistories="searchHistories"></SearchHistory>

	</div>
</template>

<script>
	import SearchHistory from './components/search-history.vue'
	import SearchSuggestion from './components/search-suggestion.vue'
	import SearchResult from './components/search-result.vue'
	import {
		getItem,
		setItem
	} from '@/utils/storage.js'

	export default {
		name: 'Search',
		components: {
			SearchHistory,
			SearchSuggestion,
			SearchResult

		},

		data() {
			return {
				searchText: '',
				isResultShow: false,
				searchHistories: getItem('serach-histories') || [],

			};
		},
		methods: {
			onSearch(val) {
				this.searchText = val

				const index = this.searchHistories.indexOf(val)
				if (index !== -1) {
					this.searchHistories.splice(index, 1)
				}
				this.searchHistories.unshift(val)
				this.isResultShow = true
			},
			onCancel() {
				this.$router.back()
			},

			clearHistory() {
				this.searchHistories = []
			},

			historySearch(val) {
				this.onSearch(val)
			}
		},
		watch: {
			searchHistories(val) {
				setItem('serach-histories', val)
			}
		}
	}
</script>

<style scoped>
	.search-container {
		padding-top: 108px;
	}
	
	.search-form {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		z-index: 3;
	}
	.van-search__action {
		color: #fff;
		background-color: #3296FA;
	}
</style>
